import { ref,reactive,watch,unref } from 'vue';
import  useLoadingEmpty  from './loading';
import { resetObject } from '@/utils/common'


export default function useList<ItemType extends Object>(
	initSearchFormData:Function|null,
	listRequestFn: Function,
	beforeList?:Function,
	afterList?:Function
) {

	const searchForm = reactive({value:getDefSearchData()});
	const list = ref<ItemType[]>([]);
	const pageObj = reactive<Common.Page<ItemType>>({
    size: 10,
    current: 1,
		total:0,
		orders:undefined
	})


	const { loading, startLoading, endLoading, empty, setEmpty } = useLoadingEmpty();



  const getList =	async()=>{
			if(beforeList)beforeList()
			startLoading()
			const { data,error } = await listRequestFn(pageObj, searchForm.value)
			if(!error){
				pageObj.total = data?.total ? data.total : 0;
				list.value = data?.records || []
				if(afterList)afterList(data)
			}
			setEmpty(!list.value.length)
			endLoading()
	}
	function handleQueryReset() {
    searchForm.value = resetObject(unref(searchForm.value),getDefSearchData())
		getList();
	}
	function handleQuery() {
		pageObj.current = 1
		getList()
	}
	function getDefSearchData(){
		return initSearchFormData?initSearchFormData():{};
	}

	  // 监听分页数据改变
	watch([
		()=>pageObj.size,
		()=>pageObj.current,
		()=>pageObj.orders,
	], () => {
		getList();
	});

	return {
    startLoading,
    endLoading,
		loading,
		empty,
		searchForm,
		list,
		pageObj,
		getList,
		handleQueryReset,
		handleQuery
	}
}


